package com.learn.blog.admin.service;

import com.learn.blog.admin.pojo.Admin;
import com.learn.blog.admin.pojo.Permission;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Package: com.learn.blog.admin.service
 * @ClassName: AuthService
 * @Author: 陈威
 * @CreateTime: 2021/9/14 21:53
 * @Description:
 */
@Service
public class AuthService {
    @Autowired
    AdminService adminService;

    public boolean auth(HttpServletRequest request, Authentication authentication) {
        //权限认证
        String requestURI = request.getRequestURI(); //获取请求路径
        Object principal = authentication.getPrincipal();  //当前用户 ==userDetails  登录时进行判断验证时候返回的用户对象
        //        anonymousUser表示匿名用户
        if (principal == null || "anonymousUser".equals(principal)) {
            //未登录
            return false;
        }
        UserDetails userDetails = (UserDetails) principal;
        String username = userDetails.getUsername();
        Admin admin = adminService.findAdminByUserName(username);
        if (admin == null) {
            return false;
        }
        //用户id  此id可以通过admin与permisssion的关联表查询该用户拥有的permisstion权限

        if (1==admin.getId()||2==admin.getId()||"陈威".equals(admin.getUsername())){
            //认为是超级管理员
            System.out.println("超级管理员 放行");
            return true;
        }
        Long id = admin.getId();
        //查询出用户拥有的权限
        List<Permission> list = adminService.findPermissionByAdminId(id);

        //获取请求访问的uri路径与用户的权限uri进行比对 如果一样 则代表该用户有权限
        //去掉uri路径后的？和参数部分
        requestURI= StringUtils.split(requestURI,'?')[0];
        for (Permission permission : list) {
            if (requestURI.equals(permission.getPath())) {
                return true;
            }
        }
        return false;
    }
}